import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QTableWidget
from PyQt5.QtCore import pyqtSlot, pyqtSignal
import pandas as pd
import akshare as ak
from typing import Callable

from pts.task_engine import TaskEngine, Task
from pts.constant import TaskType
from .Ui_bxzj_main import Ui_BxzjMain
from ..global_functions import displayDataFrame
from ..setting import SETTINGS


class BxzjMain(QWidget, Ui_BxzjMain):
    """6-北向资金 页面"""
    # 北向资金的文件名
    file_zchybk = r'Data\bxzj_zchybk.csv'
    file_zcgnbk = r'Data\bxzj_zcgnbk.csv'
    file_hgtls = r'Data\bxzj_hgtls.csv'
    file_sgtls = r'Data\bxzj_sgtls.csv'

    # 用于处理自动刷新完成信息的信号
    signal: pyqtSignal = pyqtSignal(str)

    def __init__(self, task_engine: TaskEngine, displayStatusMess: Callable):
        """初始化"""
        super(BxzjMain, self).__init__()
        self.setupUi(self)

        # 从主窗口接受到的任务引擎
        self.task_engine: TaskEngine = task_engine
        # 主窗口的信息显示函数
        self.displayStatusMess: Callable = displayStatusMess

        self.dfHgtls = None
        self.dfSgtls = None

        self.initUi()
        # 初始化与本页面相关的任务
        self.initTask()

    def initTask(self):
        """初始化与本页面相关的任务"""
        # 盘后任务
        task = Task(TaskType.ph, self.process_task, self.signal.emit, task_id=6)
        self.task_engine.put(task)

        # 为信号关联槽函数
        self.signal.connect(self.display_task)

    def process_task(self) -> str:
        """
        任务的执行函数，供任务引擎的守护线程调用
        :return: 任务执行的结果信息
        """
        return self.reloadAll(True)

    def display_task(self, mess: str):
        """
        任务执行结果的显示函数，供任务引擎的守护线程调用
        :param mess: 任务执行的结果信息
        :return: 无
        """
        # 在主窗口的状态栏上显示结果信息
        self.displayStatusMess(mess)
        # 更新页面上的列表
        self.displayAll()

    def initUi(self):
        '''初始化界面'''
        self.displayBxzjZchybk(False)
        self.displayBxzjZcgnbk(False)
        self.displayAll()

        self.tabWidget.setCurrentIndex(SETTINGS["CurrentIndex2"])

    def displayBxzjZchybk(self, reload: bool):
        if not os.path.exists(self.file_zchybk) or reload:
            try:
                stock_data = ak.stock_hsgt_board_rank_em(symbol="北向资金增持行业板块排行", indicator="今日")
                stock_data.to_csv(self.file_zchybk, index=False)
            except BaseException as ex:
                QMessageBox.information(self, '提示信息', '下载北向资金增持行业板块排行失败，可稍后重新尝试：\n{}。'.format(ex.args))
                return

        stock_data = pd.read_csv(self.file_zchybk)
        displayDataFrame(stock_data, self.twZchybk, amountList=[4, 8], startCol=1, bkKind=1, decimalList=[5, 6, 9, 10, 11], orderCol=[8, ])

    def displayBxzjZcgnbk(self, reload: bool):
        if not os.path.exists(self.file_zcgnbk) or reload:
            try:
                stock_data = ak.stock_hsgt_board_rank_em(symbol="北向资金增持概念板块排行", indicator="今日")
                stock_data.to_csv(self.file_zcgnbk, index=False)
            except BaseException as ex:
                QMessageBox.information(self, '提示信息', '下载北向资金增持概念板块排行失败，可稍后重新尝试：\n{}。'.format(ex.args))
                return

        stock_data = pd.read_csv(self.file_zcgnbk)
        displayDataFrame(stock_data, self.twZcgnbk, amountList=[4, 8], startCol=1, bkKind=2, decimalList=[5, 6, 9, 10, 11], orderCol=[8, ])

    def reloadAll(self, reload: bool) -> str:
        s = "下载北向资金数据成功。"

        if not os.path.exists(self.file_hgtls) or reload:
            try:
                self.dfHgtls = None
                self.dfHgtls = ak.stock_hsgt_hist_em(symbol="沪股通")
                self.dfHgtls.to_csv(self.file_hgtls, index=False)
            except BaseException as ex:
                s = '下载沪股通失败，可稍后重新尝试：\n{}。'.format(ex.args)

        if not os.path.exists(self.file_sgtls) or reload:
            try:
                self.dfSgtls = None
                self.dfSgtls = ak.stock_hsgt_hist_em(symbol="深股通")
                self.dfSgtls.to_csv(self.file_sgtls, index=False)
            except BaseException as ex:
                s = '下载深股通失败，可稍后重新尝试：\n{}。'.format(ex.args)

        return s

    def displayAll(self):
        s = self.reloadAll(False)
        if s != "下载北向资金数据成功。":
            QMessageBox.information(self, '提示信息', s)

        self.dfHgtls = pd.read_csv(self.file_hgtls)
        displayDataFrame(self.dfHgtls, self.twHgtls, decimalList=[4, ], orderCol=[1, 5])

        self.dfSgtls = pd.read_csv(self.file_sgtls)
        displayDataFrame(self.dfSgtls, self.twSgtls, decimalList=[4, ], orderCol=[1, 5])

        if self.dfHgtls is None or self.dfSgtls is None:
            return

        df1 = self.dfHgtls[
            [
                "日期",
                "当日成交净买额",
                "买入成交额",
                "卖出成交额",
            ]
        ]
        df1.columns = [
            "日期",
            "当日成交净买额-沪",
            "买入成交额-沪",
            "卖出成交额-沪",
        ]

        df2 = self.dfSgtls[
            [
                "当日成交净买额",
                "买入成交额",
                "卖出成交额",
            ]
        ]
        df2.columns = [
            "当日成交净买额-深",
            "买入成交额-深",
            "卖出成交额-深",
        ]

        df = pd.concat([df1, df2], axis=1)

        df['当日成交净买额'] = df['当日成交净买额-沪'] + df['当日成交净买额-深']
        df['买入成交额'] = df['买入成交额-沪'] + df['买入成交额-深']
        df['卖出成交额'] = df['卖出成交额-沪'] + df['卖出成交额-深']

        df = df[
            [
                "日期",
                "当日成交净买额",
                "买入成交额",
                "卖出成交额",
                "当日成交净买额-沪",
                "买入成交额-沪",
                "卖出成交额-沪",
                "当日成交净买额-深",
                "买入成交额-深",
                "卖出成交额-深",
            ]
        ]

        displayDataFrame(df, self.twBxls, decimalList=[1, 2, 3], orderCol=[1, 4, 7])

    @pyqtSlot()
    def on_btnRefreshBlock_clicked(self):
        self.displayBxzjZchybk(True)
        self.displayBxzjZcgnbk(True)
        QMessageBox.information(self, '提示信息', '刷新操作结束。')

    @pyqtSlot()
    def on_btnRefreshHis_clicked(self):
        s = self.reloadAll(True)
        QMessageBox.information(self, '提示信息', s)

        self.displayAll()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = BxzjMain()
    ui.show()
    sys.exit(app.exec_())
